#!/usr/bin/python2.4
#
# Copyright 2011 Google Inc. All Rights Reserved.

from google.appengine.dist import use_library
use_library('django', '1.2')
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from db import user
from libs import login_util

import os
import urllib

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

class MainPage(webapp.RequestHandler):
    def get(self):
        template_values = {}
        email = self.request.get('email')
        template_values['email'] = email
        path = os.path.join(os.path.dirname(__file__),
                            '../templates/signup.tpl')
        self.response.out.write(template.render(path, template_values))
    
    def post(self):
        email = self.request.get('email')
        password = self.request.get('password')
        if not email or not password:
            self.redirect('/staticpages/error.html?msg=' + urllib.quote('Email or password can\'t be empty!'))
            return
        first_name = self.request.get('firstName')
        last_name = self.request.get('lastName')
        nick_name = self.request.get('nickName')
        if user.HasUser(email):
            self.redirect('/staticpages/error.html?msg=' + urllib.quote('The email "%s" is already existed in our database!' % (email)))
            return
        user_profile = user.UserProfile(parent=user.UserKey(email))
        user_profile.email = email
        user_profile.password = password
        user_profile.first_name = first_name
        user_profile.last_name = last_name
        user_profile.nick_name = nick_name
        user_profile.put()
        
        login_util.LoginUtil.SetUserLogin(email)

        self.redirect('/')


application = webapp.WSGIApplication([('/signup.do', MainPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
